package com.nz.net.hays.www;

import java.io.DataOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import filechooser.FileUtils;



import android.app.Activity;
import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WelcomeWithDrawerActivity extends ActionBarActivity implements
		NavigationDrawerFragment2.NavigationDrawerCallbacks, OnClickListener  {

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment2 mNavigationDrawerFragment2;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */
	private CharSequence mTitle;
	
	// Connectivity COde Variables
	private ProgressDialog pDialog;
	int flag=0;
	JSONParser jsonParser = new JSONParser();
	private static String url = "http://hays.byethost6.com/UploadToServer.php";
	
	private String moutputusername;
	private TextView mtextviewusernme;
	private Button logout;
	ListView list1,list2;
	String a[]={"Hello","Wanna","Dance"};
	String b[]={"This","is","listview"};

		//
	
	
	
	
	//upload code
	  TextView messageText;
	    Button uploadButton;
	    int serverResponseCode = 0;
	    ProgressDialog dialog = null;
	        
	    String upLoadServerUri = null;
	     
	    /**********  File Path *************/
	     String uploadFilePath ;
	     String uploadFileName ;
	     String uploadFileSize;

	//

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome_with_drawer);
		mNavigationDrawerFragment2 = (NavigationDrawerFragment2) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer2);
		mTitle = getTitle()+"                    Hi "+moutputusername;

		// Set up the drawer.
		mNavigationDrawerFragment2.setUp(R.id.navigation_drawer2,
				(DrawerLayout) findViewById(R.id.drawer_layout2));
		
		Intent welcomeintent=getIntent();
		moutputusername=welcomeintent.getExtras().getString("username");
		mtextviewusernme = (TextView) findViewById(R.id.textviewusername);
		mtextviewusernme.setText("Hi "+moutputusername);
		logout = (Button)findViewById(R.id.buttonlogout);
		logout.setOnClickListener(this);
	

		
		//
		setupListview();
		}
	
	private void setupListView() {
		
		
	}

	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.buttonlogout)
		{
			/* SharedPreferences sharedpreferences = getSharedPreferences
				      (SignIn.MyPREFERENCES, Context.MODE_PRIVATE);
				      Editor editor = sharedpreferences.edit();
				      editor.clear();
				      editor.commit();
				      moveTaskToBack(true); 
				      WelcomeWithDrawerActivity.this.finish();*/
			
			Intent mainpage = new Intent(getApplicationContext(),MainActivity.class);
			startActivity(mainpage);
			finish();
					
		}
		
		 
		
		
		else
		{
			
			Toast.makeText(this, "This is demo for Hays", Toast.LENGTH_LONG).show();
		}
	}
	
	
	// ACTION CODE
	public void action(View v)
	{
		
		
	             
	               if(v.getId()==R.id.buttonSearch)
	       		{
	       			Intent search = new Intent(getApplicationContext(),Search.class);
	       			startActivity(search);
	       			}
		
				
	}
	
	// file chooser code 

	


	// file chooser code ends
	
	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager
				.beginTransaction()
				.replace(R.id.container,
						PlaceholderFragment.newInstance(position + 1)).commit();
	}
	
	

	public void onSectionAttached(int number) {
		switch (number) {
		case 1:
			mTitle = getString(R.string.profile_home);
			break;
		case 2:
			//mTitle = getString(R.string.profile_profile);
			Intent i = new Intent(getApplicationContext(),ProfileView.class);
			 i.putExtra("username",moutputusername);
			  startActivity(i);
			  
			break;
		case 3:
			//mTitle = getString(R.string.profile_shorlistedjobs);
			break;
		case 4:
			//mTitle = getString(R.string.profile_favouritesearch);
			break;
		case 5:
		//	mTitle = getString(R.string.profile_logout);
			break;
		case 6:
		//	mTitle = getString(R.string.profile_feedback);
			break;
		case 7:
			//mTitle = getString(R.string.profile_terms);
			break;
		}
	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle+"                    Hi "+moutputusername);
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment2.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.welcome_with_drawer, menu);
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		/*int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}*/
		return super.onOptionsItemSelected(item);
		
	
	}

	private void setupListview() {
		list1=(ListView)findViewById(R.id.list);
		list2=(ListView)findViewById(R.id.list2);
		
		 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		          android.R.layout.simple_list_item_1, android.R.id.text1, a);
		 ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
		          android.R.layout.simple_list_item_1, android.R.id.text1, b);
		 
		 // Assign adapter to ListView
	        list1.setAdapter(adapter); 
	        list2.setAdapter(adapter2);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static PlaceholderFragment newInstance(int sectionNumber) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			return fragment;
		}

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_drawer,
					container, false);
			return rootView;
		}

		@Override
		public void onAttach(Activity activity) {
			super.onAttach(activity);
			((WelcomeWithDrawerActivity) activity)
					.onSectionAttached(getArguments()
							.getInt(ARG_SECTION_NUMBER));
		}
	}

	
	
/*	public int uploadFile(String sourceFileUri) {
        
        
		String fileName = sourceFileUri;
		  String link="http://hays.byethost6.com/UploadFile.php";
        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(sourceFileUri); 
         
        if (!sourceFile.isFile()) {
             
             dialog.dismiss(); 
              
             Log.e("uploadFile", "Source File not exist :"
                                 +uploadFilePath + "" + uploadFileName);
              
             runOnUiThread(new Runnable() {
                 public void run() {
                     messageText.setText("Source File not exist :"
                             +uploadFilePath + "" + uploadFileName);
                 }
             }); 
              
             return 0;
          
        }
        else
        {
             try { 
                  
                   // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(link);
                  
                 // Open a HTTP  connection to  the URL
                 conn = (HttpURLConnection) url.openConnection(); 
                 conn.setDoInput(true); // Allow Inputs
                 conn.setDoOutput(true); // Allow Outputs
                 conn.setUseCaches(false); // Don't use a Cached Copy
                 conn.setRequestMethod("POST");
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                 conn.setRequestProperty("uploaded_file", fileName); 
                  
                 dos = new DataOutputStream(conn.getOutputStream());
        
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
              ///   dos.writeBytes("Content-Disposition: form-data; name="+fileName+";filename="+ fileName +  lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
                 
                 dos.writeBytes(lineEnd);
        
                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available(); 
        
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 buffer = new byte[bufferSize];
        
                 // read file and write it into form...
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
                    
                 while (bytesRead > 0) {
                      
                   dos.write(buffer, 0, bufferSize);
                   bytesAvailable = fileInputStream.available();
                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
                    
                  }
        
                 // send multipart form data necesssary after file data...
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        
                 // Responses from the server (code and message)
                 serverResponseCode = conn.getResponseCode();
                 String serverResponseMessage = conn.getResponseMessage();
                   
                 Log.i("uploadFile", "HTTP Response is : "
                         + serverResponseMessage + ": " + serverResponseCode);
                  
                 if(serverResponseCode == 200){
                      
                     runOnUiThread(new Runnable() {
                          public void run() {
                               
                              String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                            +" http://www.byethost6.com/htdocs/uploads/"
                                            +uploadFileName;
                               
                              messageText.setText(msg);
                              Toast.makeText(getApplicationContext(), "File Upload Complete.", 
                                           Toast.LENGTH_SHORT).show();
                          }
                      });                
                 }    
                  
                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();
                   
            } catch (MalformedURLException ex) {
                 
                dialog.dismiss();  
                ex.printStackTrace();
                 
                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("MalformedURLException Exception : check script url.");
                        Toast.makeText(getApplicationContext(), "MalformedURLException", 
                                                            Toast.LENGTH_SHORT).show();
                    }
                });
                 
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
            } catch (Exception e) {
                 
                dialog.dismiss();  
                e.printStackTrace();
                 
                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(getApplicationContext(), "Got Exception : see logcat ", 
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                                                 + e.getMessage(), e);  
            }
            dialog.dismiss();       
            return serverResponseCode; 
             
         } // End else block 
       } 
	 
		class loginAccess extends AsyncTask<String, String, String> {
	
			private static final String TAG_SUCCESS="success";
		
	
			protected void onPreExecute() {
				super.onPreExecute();
				pDialog = new ProgressDialog(WelcomeWithDrawerActivity.this);
				pDialog.setMessage("Wait...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(true);
				pDialog.show();
			}
			@Override
			protected String doInBackground(String... arg0) {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("name",uploadFileName));
				params.add(new BasicNameValuePair("tmp_name",uploadFileName));
				params.add(new BasicNameValuePair("size",uploadFileSize));
				
				
				// Disposition code
				HttpURLConnection conn = null;
		        DataOutputStream dos = null;  
		        String lineEnd = "\r\n";
		        String twoHyphens = "--";
		        String boundary = "*****";
		        int bytesRead, bytesAvailable, bufferSize;
		        byte[] buffer;
		        int maxBufferSize = 1 * 1024 * 1024; 
				
				
				try { 
	                  
	                   // open a URL connection to the Servlet
	                 FileInputStream fileInputStream = new FileInputStream(uploadFilePath+"/"+uploadFileName);
	                URL newurl = new URL(url);
	                  
	                 // Open a HTTP  connection to  the URL
	                 conn = (HttpURLConnection) newurl.openConnection(); 
	                 conn.setDoInput(true); // Allow Inputs
	                 conn.setDoOutput(true); // Allow Outputs
	                 conn.setUseCaches(false); // Don't use a Cached Copy
	                 conn.setRequestMethod("POST");
	                 conn.setRequestProperty("Connection", "Keep-Alive");
	                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
	                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
	                 conn.setRequestProperty("uploaded_file", uploadFileName); 
	                  
	                 dos = new DataOutputStream(conn.getOutputStream());
	        
	                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
	              ///   dos.writeBytes("Content-Disposition: form-data; name="+fileName+";filename="+ fileName +  lineEnd);
	                 dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ uploadFileName + "\"" + lineEnd);
	                 
	                 dos.writeBytes(lineEnd);
	        
	                 // create a buffer of  maximum size
	                 bytesAvailable = fileInputStream.available(); 
	        
	                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
	                 buffer = new byte[bufferSize];
	        
	                 // read file and write it into form...
	                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
	                    
	                 while (bytesRead > 0) {
	                      
	                   dos.write(buffer, 0, bufferSize);
	                   bytesAvailable = fileInputStream.available();
	                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
	                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);   
	                    
	                  }
	        
	                 // send multipart form data necesssary after file data...
	                 dos.writeBytes(lineEnd);
	                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	        
	                 // Responses from the server (code and message)
	                 serverResponseCode = conn.getResponseCode();
	                 String serverResponseMessage = conn.getResponseMessage();
	                   
	                 Log.i("uploadFile", "HTTP Response is : "
	                         + serverResponseMessage + ": " + serverResponseCode);
	                  
	                 if(serverResponseCode == 200){
	                      
	                     runOnUiThread(new Runnable() {
	                          public void run() {
	                               
	                              String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
	                                            +" http://www.byethost6.com/htdocs/uploads/"
	                                            +uploadFileName;
	                               
	                              messageText.setText(msg);
	                              Toast.makeText(getApplicationContext(), "File Upload Complete.", 
	                                           Toast.LENGTH_SHORT).show();
	                          }
	                      });                
	                 }    
	                  
	                 //close the streams //
	                 fileInputStream.close();
	                 dos.flush();
	                 dos.close();
	                   
	            } catch (MalformedURLException ex) {
	                 
	                dialog.dismiss();  
	                ex.printStackTrace();
	                 
	                runOnUiThread(new Runnable() {
	                    public void run() {
	                        messageText.setText("MalformedURLException Exception : check script url.");
	                        Toast.makeText(getApplicationContext(), "MalformedURLException", 
	                                                            Toast.LENGTH_SHORT).show();
	                    }
	                });
	                 
	                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
	            } catch (Exception e) {
	                 
	                dialog.dismiss();  
	                e.printStackTrace();
	                 
	                runOnUiThread(new Runnable() {
	                    public void run() {
	                        messageText.setText("Got Exception : see logcat ");
	                        Toast.makeText(getApplicationContext(), "Got Exception : see logcat ", 
	                                Toast.LENGTH_SHORT).show();
	                    }
	                });
	                Log.e("Upload file to server Exception", "Exception : "
	                                                 + e.getMessage(), e);  
	            }
				
				
				
				
				
				
				
				
				// Disposition ends here
				
				JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
				Log.d("Create Response", json.toString());
				
				try {
					int success = json.getInt(TAG_SUCCESS);
					if (success == 1) 
					 {
						flag=0;
						 
					 }
					 else
					 {
						flag=1;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				return null;
			}
			protected void onPostExecute(String file_url) {
				pDialog.dismiss();
				if(flag==1)
					{
					Toast.makeText(WelcomeWithDrawerActivity.this,"Data Not Found", Toast.LENGTH_LONG).show();
					}
				else
				{
					 messageText.setText(uploadFileSize);
					/* try {
						uploadFile(uploadFilePath+"/"+uploadFileName);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Toast.makeText(WelcomeWithDrawerActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
					}//
				}
				
			}
			
		  }*/

	
	
}
